import { $ } from './jquery-module.js';
import cookie from './library/cookie.js';
$('header').load('./header_module.html');
$('footer').load('./floor_module.html');
$(function() {
    let value;
    /*数据接收*/
    let reg = /^.+\?/i;
    let id = location.href.replace(reg, '').slice(3);
    let o = {
        prevButton: '.swiper-button-prev',
        nextButton: '.swiper-button-next',
        noSwiping: true,
        noSwipingClass: 'stop-swiping',
        slidesPerView: 'auto',
        paginationClickable: true,
        spaceBetween: 0,
        freeMode: false
    };
    let swiper;
    /*获取登录用户信息*/
    if (cookie.get('user')) {
        $('.list:last li:first').html(`<a href="javaScript:;">${cookie.get('user')}</a><div class="userBox">
        <section>
            <img src="../img/头像.png" alt="">
            <div>
                <p><em></em><span></span></p>
                <div>
                    <a href="javascript:;"><em></em> 未实名</a><a href="javascript:;"><em></em>消息</a></div>
            </div>
        </section>
        <section>
            <dl>
                <dt><span>我的订单</span><a href="javaScript:;">更多</a></dt>
            </dl>
            <ul>
                <li><a href="javaScript:;">待付款</a></li>
                <li><a href="javaScript:;">待收货</a></li>
                <li><a href="javaScript:;">待评价</a></li>
                <li><a href="javaScript:;">退换货</a></li>
                <li><a href="javaScript:;">旧机回收</a></li>
            </ul>
        </section>
        <section>
            <a href="javaScript:;"><span>0</span><span>积分</span></a><a href="javaScript:;"><span>0</span><span>优惠券</span></a><a href="javaScript:;"><span>0.00</span><span>代金券</span></a>
        </section>
        <button>退出登录</button></div>`);
        $('.list:last li:first').addClass('drop-down users');
        /*退出登录事件*/
        $('.list:last li:first button').click(function() {
                cookie.set('user', '');
                location.href = './index.html';
            })
            /*加入购物车事件*/
        $('.shopping-btn').click(function() {
            let s_price = $('.j-g').text(),
                s_num = $('.pro-num').prev().val(),
                s_title = $('.pro-name').text(),
                s_color = $('.selectColor').text(),
                s_version;
            if ($('.selectVersion').length) {
                s_version = $('.selectVersion').text();
            } else {
                s_version = null;
            }
            if (id.length > 1) {
                id = id.slice(0, -1);
            }
            addItem(id, s_title, s_price, s_num, s_color, s_version, colorImg, res.hasInstallment)
        })
    } else {
        $('.list:last li:first').html(`<a href="../html/login.html">请登录</a>&nbsp;<a href="../html/reg.html">注册</a>`);
        $('.list:last li:first').removeClass('drop-down users');
        $('.shopping-btn').click(function() {
            let ok = confirm('无法加入购物车，请先进行登录！谢谢！');
            if (ok) {
                location.href = './login.html';
            }
        })
    }
    $.get('../../interface/productData.php', { id }, function(res) {
        res = JSON.parse(res);
        let temp = '',
            temp1 = '<li><div>选择版本</div></li>',
            temp2 = '<li><div>选择颜色</div></li>',
            temp3 = '',
            code = '',
            temp4 = '<li><div>推荐</div></li>';
        let version = JSON.parse(res.version),
            picture = JSON.parse(res.picture),
            colorImg = JSON.parse(res.colorImg);
        /*标题 */
        console.log(res.title)
        $('.type').html(JSON.parse(res.title).type);
        $('.active').html(JSON.parse(res.title).text);

        /*促销*/
        JSON.parse(res.promotion).forEach(elm => {
            temp += `<div><span>${elm.name}</span>${elm.text}</div>`;
        })
        $('.c-x').html(temp);
        /*选择版本 */
        version.forEach(elm => {
            if (elm.version == '无线充版' || elm.version == '新年版') { //设置默认版本
                temp1 += `<li><p class="p-active">${elm.version}</p></li>`;
            } else {
                temp1 += `<li><p>${elm.version}</p></li>`;
            }
        })
        $('.p-version').html(temp1);
        $('.p-version p').click(function() {
            let _this = $(this);
            $('.p-version p').removeClass('p-active');
            _this.addClass('p-active');
            productCode(res, version, _this, code, 'Version');
            priceChange();
        });
        /*商品颜色vs图片 */
        picture.forEach(elm => {

            if (elm.color == '冰霜银' || elm.color == '新年红' || elm.color == '密语红' || elm.color == '樱语粉' || elm.color == '精灵蓝') { //设置默认颜色
                temp2 += `<li>
                <p class="p-active"><img src="${elm.src}" alt="">${elm.color}</p>
            </li>`
            } else {
                temp2 += `<li>
            <p><img src="${elm.src}" alt="">${elm.color}</p>
        </li>`;
            }
        });
        $('.p-color').html(temp2);
        if ($('.p-color .p-active')) {
            colorImg.forEach(function(elm) {
                if (elm.color == `${$('.p-color').children().children('.p-active').text()}`) {
                    elm.src.forEach(function(e) {
                        temp3 += `<div class="swiper-slide stop-swiping"><img src="${e}" alt=""></div>`;
                    })
                }
            })
            $('.swiper-wrapper').html(temp3);
            $('.pro-left>div:first-child').html(`<img src="${$('.swiper-slide:first-child').children().attr('src')}" alt="">`);
            swiperSlide();
            swiper = new Swiper('.swiper-container', o);
        }

        $('.p-color p').click(function() {
            temp3 = "";
            $('.p-color p').removeClass('p-active');
            $(this).addClass('p-active');
            let _this = $(this);
            colorImg.forEach(function(elm) {
                if (elm.color == `${_this.text()}`) {
                    elm.src.forEach(function(e, i) {
                        if (i == 0) {
                            temp3 += `<div class="swiper-slide stop-swiping p-active"><img src="${e}" alt=""></div>`;
                        } else {
                            temp3 += `<div class="swiper-slide stop-swiping"><img src="${e}" alt=""></div>`;
                        }
                    })
                }
            })
            $('.swiper-wrapper').html(temp3);
            $('.pro-left>div:first-child').html(`<img src="${$('.swiper-slide:first-child').children().attr('src')}" alt="">`);
            swiperSlide();
            swiper = new Swiper('.swiper-container', o);
            productCode(res, version, _this, code, 'Color');

        })

        /*价格 */
        function priceChange() {
            version.forEach(elm => { //初始化
                if (!elm.price) {
                    $('.j-g').text(`￥${parseInt(res.price).toFixed(2)}`);
                } else {
                    if (elm.version == $('.p-version .p-active').text()) {
                        $('.j-g').text(`￥${parseInt(elm.price).toFixed(2)}`);
                    }
                }
            });
        }
        priceChange();
        /*分期免息 */
        if (res.hasInstallment == '1') {
            $('.p-installment').css('display', 'block');
            $('.p-installment').html(`<li>
            <div>分期免息</div>
        </li>
        <li>
            <p>花呗分期<i></i></p>
            <div class="Ant-CheckLater install">
                <ul>
                    <li>
                        <p class="price price1"><span>￥368</span>x 3期</p>
                        <p>免息，0手续费</p>
                    </li>
                    <li>
                        <p class="price price2"><span>￥368</span>x 3期</p>
                        <p>免息，0手续费</p>
                    </li>
                    <li>
                        <p class="price price3"><span>￥368</span> × 3期</p>
                        <p>免息，0手续费</p>
                    </li>
                </ul>
                <div>
                    <h2>花呗分期是什么？</h2>
                    <p class="explain1">花呗分期是蚂蚁金服（支付宝公司）提供的先消费后分期还款的赊购服务。</p>
                    <p class="explain2">免息活动适用于单款免息商品订单，含多款商品订单仅在免息活动一致时可享用。</p>
                </div>
                <div class="free-btn">
                    <a href="javaScript:;" class="ant-btn">分期购买</a>
                </div>
            </div>
        </li>
        <li>
            <p>掌上生活分期<i></i></p>
            <div class="handheld-life  install">
                <ul>
                    <li class="p-active">
                        <p class="price price1"><span>￥368</span>x 3期</p>
                        <p>免息，0手续费</p>
                    </li>
                    <li>
                        <p class="price price2"><span>￥368</span>x 3期</p>
                        <p>免息，0手续费</p>
                    </li>
                    <li>
                        <p class="price price3"><span>￥368</span> × 3期</p>
                        <p>免息，0手续费</p>
                    </li>
                </ul>
                <div>
                    <h2>掌上生活分期是什么？</h2>
                    <p class="explain1">掌上生活分期是招商银行信用卡中心提供的消费分期服务。</p>
                    <p class="explain2">免息活动适用于单款免息商品订单，含多款商品订单仅在免息活动一致时可享用。</p>
                </div>
                <div class="free-btn">
                    <a href="javaScript:;" class="life-btn">分期购买</a>
                </div>
            </div>
        </li>`);
            $('.install li').click(function() {
                $(this).toggleClass('p-active');
                $(this).siblings().removeClass('p-active');
                installChange($('.Ant-CheckLater li').hasClass('p-active'), '.ant-btn');
                installChange($('.handheld-life li').hasClass('p-active'), '.life-btn');
            })

            function installChange(trueFalse, Class) {
                if (trueFalse) {
                    $(Class).css({
                        'backgroundColor': '#ca151d',
                        'cursor': 'pointer'
                    });
                } else {
                    $(Class).css({
                        'backgroundColor': '#efb8bb',
                        'cursor': 'not-allowed'
                    });
                }
            }
        }
        /*商品推荐*/
        JSON.parse(res.recommoned).forEach(elm => {
            temp4 += `<li><a href="#">${elm.text}</a></li>`
        });
        $('.p-recommoned').html(temp4);
        /*已选商品/商品模块初始化 */
        productCode(res, version, null, code, 'Color');
    });

    /* swiper-slide块*/
    function swiperSlide() {
        $('.swiper-slide').click(function() {
            let src = $(this).children().attr('src');
            $('.img').children('img').attr('src', `${src}`);
        });
        $('.swiper-slide').hover(function() {
            $(this).css('border', '1px solid crimson');
            $(this).siblings().css('border', '0');
        });
    }
    /*商品编码块-已选择商品-补全标题 */
    function productCode(res, version, _this, code, type) {
        let _text, thisText;
        if (_this) {
            thisText = _this.text();
        } else {
            thisText = $('.p-color .p-active').text();
        }
        if (type == 'Color') {
            _text = $('.p-version .p-active').text();
        } else if (type == 'Version') {
            _text = $('.p-color .p-active').text();
            [_text, thisText] = [thisText, _text];
        }
        if ($('.title-version').length) {
            $('.title-version').text(_text);
        }
        $('.title-color').text(thisText);
        $('.p-select').children().last().text(thisText);
        if (res.hasVersion == '1') {
            version.filter(elm => {
                if (elm.version == _text) {
                    return elm;
                };
            })[0].color.forEach(elm => {
                if (elm.color == thisText) {
                    code = elm.code;
                }
            })
            $('.p-select').children().first().text(_text);
        } else {
            $('.p-version').css('display', 'none');
            version.forEach(elm => {
                if (elm.color[0].color == thisText) {
                    code = elm.color[0].code;
                }
            })
            $('.p-select').html(`<span class="selectColor">${thisText}</span>`);

        }
        $('.p-code').text(code);
    }
    /*加入购物车块 */
    function addItem(id, title, price, num, color, version, colorImg, install) {
        let shop = cookie.get('shop');
        let img;
        colorImg.forEach(elm => {
            if (elm.color == color) {
                img = elm.src[0];
            }
        })

        let product = {
            id,
            img,
            title,
            version,
            color,
            price,
            num,
            install
        }
        console.log(product)
        if (shop) {
            shop = JSON.parse(shop);
            if (shop.some(el => el.id === id) && shop.some(el => el.color === color) && shop.some(el => el.version === version)) {
                shop.forEach(elm => {
                    elm.id === id ? elm.num = num : null;
                });
            } else {
                shop.push(product);
            }
        } else {
            shop = [];
            shop.push(product);
        }
        cookie.set('shop', JSON.stringify(shop), 1);
    }

    /*商品购买数量*/
    setInterval(function() {
        value = $('.pro-num').prev().val();
        if (value != '1') {
            $('.pro-num').children().last().css({ 'cursor': 'pointer', 'color': 'rgb(119, 113, 113)' });
        } else {
            $('.pro-num').children().last().css({ 'cursor': 'not-allowed', 'color': '#ddd' });
        }
        if ($('.pro-num').prev().attr('max') != value) {
            $('.pro-num').children().first().css({ 'cursor': 'pointer', 'color': 'rgb(119, 113, 113)' });
        } else {
            $('.pro-num').children().first().css({ 'cursor': 'not-allowed', 'color': '#ddd' });
        }
    })
    $('.pro-num').children().last().css('cursor', 'not-allowed');
    $('.pro-num').children().first().click(function() {
        value = $('.pro-num').prev().val();
        if ($('.pro-num').prev().attr('max') != value) {
            value = parseInt(value) + 1;
            $('.pro-num').prev().val(value);
        }

    });
    $('.pro-num').children().last().click(function() {
        value = $('.pro-num').prev().val();
        if (value != '1') {
            value = parseInt(value) - 1;
            $('.pro-num').prev().val(value);
        }

    });
    /*搜索*/
    $('.form-control').focus(function() {
        $('.key-search').css('display', 'none');
    });
    $('.form-control').focusout(function() {
        $('.key-search').css('display', 'inline-block');
    });

    function searchChange(fn) {
        let timer;
        return function() {
            if (!timer) {
                timer = setTimeout(function() {
                    fn();
                    timer = null;
                }, 500);

            }
        }
    }

    function fn() {
        let search = $('.form-control').val();
        $.post('../../interface/search.php', { search }, function(response) {
            let content = '';
            if (response) {
                response = JSON.parse(response);
                response.forEach(elm => {
                    content += `<li><a href='../html/product.details.html?id=${elm.id}'>${elm.search}</a></li>`;
                })
            }
            $('.search-result').html(content);
        })
    }
    $('.form-control').on('input', searchChange(fn));
})